import frappe
from frappe import _
from erpnext.controllers import website_list_for_contact
from erpnext.controllers.website_list_for_contact import post_process as original_post_process

def custom_post_process(doctype,data):
    result = original_post_process(doctype,data)

    for doc in result:
        if doc.status == 'To Deliver and Bill':
                doc.status = _('To Deliver and Bill')
        if doc.status == 'Completed':
                doc.status = _('Completed')
        if doc.status == 'To Deliver':
                doc.status = _('To Deliver')
        if doc.status == 'To Bill':
                doc.status = _('To Bill')
        if doc.status == 'Per Delivered':
                doc.status = _('Per Delivered')
        if doc.get('doctype') == 'Sales Order' and doc.get('per_delivered',0) <= 0:
            po_list = frappe.get_all('Purchase Order Item',
                                        filters = {
                                            'sales_order': doc.name,
                                            'docstatus':1
                                        },
                                        fields = ['parent','qty','received_qty']
            )
            if not po_list:
                doc.status = _('To Purchase')
            elif any(True for row in po_list if (row.qty - row.received_qty) > 0):
                doc.status = _('To Receive')
    return result

website_list_for_contact.post_process = custom_post_process
            